<template>
	<view class="container">
		<view class="head-box">
			<view class="top">
				<view class="left">
					<view class="img-box">
						<image class="img" src="/static/img/my/avatar.png">
						</image>
					</view>
					<view class="name">
						{{userStore.accountInfo?.username}}
					</view>
				</view>
				<view class="right" @click="changeCart">
					<view class="code">
						{{nowCart.hphm}}
					</view>

					<Button2 v-if="nowCart.energyType === '燃油'" class="type">燃油</Button2>
					<Button2 v-else class="type green">新能源</Button2>
					<image class="change-icon" src="/static/img/common/change.png"></image>
				</view>
			</view>
			<view class="btns">
				<view class="btn" :class="btn === activeBtn && 'active'" @click="changeActiveBtn(btn)"
					v-for="btn in btns" :key="btn">
					<text>{{btn}}</text>
					<view class="line"></view>
				</view>
			</view>
		</view>
		<scroll-view scroll-y class="scroll-box">
			<MissionItem v-for="item in orderList" @btnClick="btnClick(item)" :info="item" :key="item.id" />
		</scroll-view>
		<!-- 出场确认 -->
		<Popup1 v-if="isShowStartPopup" type='1' :list="startList" @offPopup="offStartPopup" />
		<!-- 到场确认 -->
		<Popup1 v-if="isShowEndPopup" type='2' :list="endList" @offPopup="offEndPopup" />
		<!-- 地址导航确认 -->
		<Popup1 v-if="isShowAddrPopup" type='3' :list="addrList" @offPopup="offAddrPopup" />
		<!-- 警告提示 -->
		<Popup2 ref="myPopup2" @offPopup="offStartTipPopup" />
		<messageTip ref="myMessage"></messageTip>
	</view>
</template>

<script setup lang="ts">
	import { ref, watchEffect } from 'vue';
	import Button2 from '@/components/button2/button2.vue';
	import MissionItem from '@/components/drivers/missionItem/missionItem.vue';
	import Popup1 from '@/components/drivers/popup1/popup1.vue';
	import Popup2 from '@/components/drivers/popup2/popup2.vue';
	import { useUserStore, useDriverStore } from '@/stroes';
	import * as driverApi from '@/api/drivers/driver.js'
	// 提示
	const myMessage = ref()
	// 弹窗
	const myPopup2 = ref()
	// 仓库
	const userStore = useUserStore()
	const driverStore = useDriverStore()
	// 改变车辆
	const changeCart = () => {
		uni.navigateTo({
			url: '/pages/drivers/selectCart/selectCart?type=1'
		})
	}
	// 订单列表
	// 是否有联单
	const hasOrder = ref(true)
	const orderList = ref([])
	const nowItem = ref({})
	// const nowItem2 = ref({})
	// const startList = ref([])
	// info.type 1--待执行 2--已完成  3--执行中 4--计划拉运
	// 获取列表
	const getProjectList = (type : string) => {
		return new Promise((res, rej) => {
			if (type === '执行中') {
				driverApi.getProjectList({ plateNo: userStore.nowCart?.hphm, transportStatus: ['1'] }).then(res1 => {
					if (res1.data && res1.data.code === 0) {
						res(res1.data.data.map(item => ({ ...item, type: 3 })))
					} else {
						rej(res1)
					}
				})
			} else if (type === '已完成') {
				driverApi.getProjectList({ plateNo: userStore.nowCart?.hphm, transportStatus: ['2', '3'] }).then(res1 => {
					if (res1.data && res1.data.code === 0) {
						res(res1.data.data.map(item => ({ ...item, type: 2 })))
					} else {
						rej(res1)
					}
				})
			} else if (type === '待执行') {
				driverApi.getPendingList({ plateNo: userStore.nowCart?.hphm }).then(res1 => {
					if (res1.data && res1.data.code === 0) {
						if (res1.data.data) {
							hasOrder.value = true
							res([{ ...res1.data.data, type: 1 }]);
							getStartMessage(res1.data.data)
						} else {
							hasOrder.value = false

						}
						driverApi.getStartProject({ plateNo: userStore.nowCart?.hphm }).then(res2 => {
							if (res2.data && res2.data.code === 0) {
								let arr = res2.data.data.map(item => ({ ...item, type: 4, hphm: userStore.nowCart?.hphm }))
								if (!hasOrder.value) {
									res(arr)
								}
								startList.value = arr
							} else {
								rej(res2)
							}
						})
					} else {
						rej(res1)
					}
				})
			}
			else if (type === '全部') {
				driverApi.getProjectList({ plateNo: userStore.nowCart?.hphm, transportStatus: [] }).then(res1 => {
					if (res1.data && res1.data.code === 0) {
						res(res1.data.data.map(item => ({ ...item, type: 2 })))
					} else {
						rej(res1)
					}
				})
			}
		})
	}
	// btn列表
	const btns = ['待执行', '执行中', '已完成', '全部'];
	// 当前btn
	const activeBtn = ref('待执行');

	// 改变当前btn
	const changeActiveBtn = async (btn : string) => {
		activeBtn.value = btn
		uni.showLoading({
			title: '数据加载中...'
		})
		try {
			if (btn === '全部') {
				let arr = []
				let list : any[] = await getProjectList('待执行');

				if (list && list.length) {
					arr.push(...list)
				}
				let list2 : any[] = await getProjectList('全部');
				if (list2 && list.length) {
					arr.push(...list2)
				}
				orderList.value = arr

			} else {
				let list : any[] = await getProjectList(btn)
				// console.log('111111', list);
				if (list) {
					orderList.value = list
				} else {
					orderList.value = []
				}
			}
		} catch (e) {
			orderList.value = []
			// console.log('cccccccccc');
			// myMessage.value.open('error', e.data?.msg)
		} finally {
			uni.hideLoading()
		}
		// console.log(orderList.value);
	}
	// changeActiveBtn('待执行')
	// 当前车辆信息
	const nowCart = ref(userStore.nowCart)
	watchEffect(() => {
		if (userStore.nowCart) {
			nowCart.value = userStore.nowCart;
			changeActiveBtn(activeBtn.value)
		}
	})

	// 获取出场提示
	let timer = null
	const getStartMessage = (order : any) => {
		if (timer) {
			clearInterval(timer)
			timer = null
		}
		if (order.createTime) {
			let nowTime = new Date().getTime();
			let startTime = new Date(order.createTime).getTime();
			if (nowTime > startTime) {
				if (startList.value.length) {
					let nowProject = startList.value.find(item => item.id === order.planId)
					if (nowProject) {
						let tipTime = nowProject.prospectTime * 0.3 * 60 * 1000;
						let tipTime2 = startTime + tipTime;
						if (tipTime2 > nowTime) {
							showStartPopup()
						}
					}
				}
			}
		}
		timer = setInterval(async () => {
			let list = await getProjectList('执行中') as []
			if (!isShowStartPopup.value && !list.length) {
				showStartPopup()
			}
			if (list.length) {
				clearInterval(timer)
				timer = null
			}
		}, 120000)
	}
	// 出场确认
	const isShowStartPopup = ref(false)
	// 出场项目列表
	const startList = ref([]);
	// 显示出场确认弹窗
	const showStartPopup = () => {
		isShowStartPopup.value = true
	}

	// 关闭出场项目弹窗
	const offStartPopup = (project : any) => {
		isShowStartPopup.value = false
		if (project) {
			if (!hasOrder.value) {
				nowItem.value = project.nowAddr;
			}
			// console.log('yyyyyyyyyy', project);
			getAddrList().then(res => {
				// console.log('出场确认，，', res);
				if (res === 0) {
					sendStartProject()
				}
			})
		}
	}
	// 发送出场确认
	const sendStartProject = () => {
		return new Promise((res, rej) => {
			uni.showLoading({
				title: '出场确认中...'
			})
			console.log('nowItem', nowItem.value);
			uni.getLocation({
				type: 'gcj02',
				success: function (res1) {
					let obj = {}
					if (hasOrder.value) {
						obj = {
							...nowItem.value,
							longitude: res1.longitude,
							latitude: res1.latitude,
						}
					} else {
						obj = {
							longitude: res1.longitude,
							latitude: res1.latitude,
							hphm: nowItem.value.hphm,
							planId: nowItem.value?.id,
						}
					}

					driverApi.outCompleted(obj).then(res2 => {
						if (res2.data && res2.data.code === 0) {
							myMessage.value.open('success', '出场确认完成')
							changeActiveBtn(activeBtn.value)
						}
					})
				},
				fail(err) {
					uni.showToast({
						title: err?.errMsg,
						icon: 'none'
					})
				},
				complete() {
					uni.hideLoading()
					res(1)
				}
			});
		})
	}
	// 到场确认
	const isShowEndPopup = ref(false)
	// 到场项目列表
	const endList = ref([]);
	// 关闭到场项目弹窗
	const offEndPopup = (data : any) => {
		const cartData = data.nowAddr
		if (cartData) {
			let obj = { orderId: nowItem.value.id, terminalId: cartData.id, terminalPlace: cartData.terminalPointName }
			if (hasOrder.value) {
				obj.createTime = nowItem.value.createTime
			}
			console.log('到场确认', obj);
			// 到场确认
			driverApi.upCompleted(obj).then(res => {
				// console.log('出场完成', res);
				if (res.data && res.data.code === 0) {
					myMessage.value.open('success', res.data.msg);
					changeActiveBtn(activeBtn.value)
				}
				isShowEndPopup.value = false
			})
		} else {
			// 取消
			isShowEndPopup.value = false
		}

	}
	// 获取到场项目
	const getEndProject = () => {
		driverApi.getEndProject({ planId: nowItem.value.planId }).then(res => {
			// console.log('yyyyyyyyy', res);
			if (res.data && res.data.code === 0) {
				if (res.data.data?.terminalPointList && res.data.data?.terminalPointList.length) {
					endList.value = res.data.data?.terminalPointList.map(item => ({ ...item, startingPlace: item.terminalPointName }))
					isShowEndPopup.value = true
				} else {
					driverApi.getAllEnd().then(res2 => {
						// console.log('所有终点', res2);
						if (res2.data && res2.data.code === 0) {
							endList.value = res2.data.data.map(item => ({ ...item, startingPlace: item.terminalPointName }))
							isShowEndPopup.value = true
						}
					})
				}
			}

		})
	}
	// 是否显示终点弹窗
	const isShowAddrPopup = ref(false)
	// 终点列表
	const addrList = ref([])
	// 获取终点列表
	const getAddrList = () => {
		return new Promise((res, rej) => {
			driverApi.getEndProject({ planId: nowItem.value?.id || nowItem.value?.planId }).then(res3 => {
				// console.log('res3: ', res3);
				if (res3.data && res3.data.code === 0) {
					if (res3.data.data) {
						addrList.value = res3.data?.data?.terminalPointList.map(item => ({ ...item, startingPlace: item.terminalPointName }))
						if (addrList.value.length) {
							myPopup2.value.open('是否需要导航', 1)
							res(addrList.value.length)
						} else {
							res(0)
						}
					} else {
						res(0)
					}
				}
			})
		})
	}
	// 关闭终点弹窗
	const offAddrPopup = (obj) => {
		if (obj.location === 1 && obj.type === 1) {
			sendStartProject().then(res => {
				let location = JSON.parse(obj.nowAddr.electronicFence)
				if (location !== '') {
					location = location.data[0]
				} else {
					location = []
				}
				uni.openLocation({
					latitude: location[1],
					longitude: location[0],
					name: obj.nowAddr.terminalPointName,
					address: obj.nowAddr.terminalPointAddress,
				})
			})
		} else {
			isShowAddrPopup.value = false;
			sendStartProject()
		}

	}

	// 提示文字
	const startTipText = ref('系统检测到您的车载GPS与APP的GPS已经分隔超过 <text style="color:#EB4F51;">500</text> 米，不能进行操作！')
	// 关闭提示弹窗
	const offStartTipPopup = async (type : number, status : number) => {
		// 1--是否需要导航  2--gps检测
		if (type == 1) {
			// 确认需要导航
			myPopup2.value.close()
			if (status == 1) {
				isShowAddrPopup.value = true;
			} else {
				sendStartProject()
			}
		} else {
			myPopup2.value.close()
		}

	}
	// 列表按钮点击---出场确认--1  查看详情--2  到场确认--3
	const btnClick = (item : any) => {
		nowItem.value = item;
		// console.log('11111', item);
		if (item.type === 1 || item.type === 4) {
			// 有联单
			if (hasOrder.value) {
				showStartPopup()
			} else {
				try {
					sendStartProject()


				} catch (error) {
					uni.showToast({
						title: error,
						icon: 'none'
					})
				}


			}
			// console.log('获取出场确认列表，显示出场确认弹窗');
		} else if (item.type === 2) {
			driverStore.nowItem = item
			uni.navigateTo({
				url: '/pages/drivers/missionDetail/missionDetail'
			})
		} else if (item.type === 3) {
			// console.log('获取到场确认列表，显示到场确认弹窗');
			getEndProject()
		}
	}
</script>

<style scoped lang="scss">
	.head-box {
		padding-top: 102rpx;
		border-radius: 0rpx 0rpx 32rpx 32rpx;
		background: linear-gradient(59deg, #438DFF 0%, #056FFF 100%);

		.top {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				display: flex;
				align-items: center;

				.img-box {
					margin-left: 32rpx;
					width: 112rpx;
					height: 112rpx;
					border: 2rpx solid #fff;
					border-radius: 50%;

					.img {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}



				.name {
					margin: 0rpx 32rpx 0rpx 24rpx;
					font-size: 32rpx;
					color: #fff;
				}
			}

			.right {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 26rpx 36rpx 26rpx 26rpx;
				border-radius: 48rpx 0rpx 0rpx 48rpx;
				background-color: #fff;
				white-space: nowrap;

				.code {
					font-size: 36rpx;
					font-weight: 500;
					color: $primary-color;
				}

				.type {
					margin-left: 18rpx;
					margin-right: 32rpx;
					padding: 0 18rpx;
					line-height: 40rpx;
				}

				.change-icon {
					width: 42rpx;
					height: 42rpx;
				}
			}
		}

		.btns {

			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 32rpx 28rpx;

			.btn {
				font-size: 28rpx;
				color: #B8D5FB;

				.line {
					display: none;
					margin: 6rpx auto 0rpx;
					// margin-top: 6rpx;
					width: 20rpx;
					height: 4rpx;
					border-radius: 8rpx;
					background-color: #fff;

				}

				&.active {
					font-size: 32rpx;
					color: #fff;

					.line {
						display: block;
					}
				}
			}
		}
	}

	.scroll-box {
		padding: 20rpx 32rpx 32rpx;
		height: 1100rpx;
		box-sizing: border-box;
		// background-color: skyblue;
	}
</style>